package com.boot.web.action;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.boot.beans.Course;
import com.boot.beans.CourseComment;
import com.boot.beans.Question;
import com.boot.beans.QuestionItem;
import com.boot.beans.SimpleUser;
import com.boot.beans.UserQuestion;
import com.boot.common.BaseAction;
import com.boot.web.service.CourseCommentService;
import com.boot.web.service.CourseService;
import com.boot.web.service.IndexImageService;
import com.boot.web.service.QuestionItemService;
import com.boot.web.service.QuestionService;
import com.boot.web.service.SimpleUserService;
import com.boot.web.service.UserQuestionService;

import util.Constant;
import util.DateUtil;
import util.FieldUtil;
import util.FileUtil;
import util.MapUtil;
import util.MathExtend;
import util.Page;

@Controller
@RequestMapping("/com")
public class WebAction extends BaseAction {

	@Autowired
	private SimpleUserService			simpleUserService;
	@Autowired
	private CourseService					courseService;
	@Autowired
	private IndexImageService			indexImageService;
	@Autowired
	private CourseCommentService	courseCommentService;
	@Autowired
	private QuestionService				questionService;
	@Autowired
	private UserQuestionService		userQuestionService;
	@Autowired
	private QuestionItemService		questionItemService;

	@RequestMapping(value = "/downloadVideo.do")
	public String downloadVideo(int uid) {
		try {
			Course item = courseService.get(uid);
			FileUtil.download(request, response, getResourceFile() + File.separator + item.getVideoFile(), Constant.CONTENTTYPE_OCTET_STREAM,
					item.getVideoFile());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping(value = "/cuoti.do")
	public String cuoti() {
		try {
			List<Question> list = new ArrayList<Question>();
			List<UserQuestion> selectAll = userQuestionService.selectAll(UserQuestion.class,
					MapUtil.createMap("userId", getSimpleUser().getId()));
			for (UserQuestion userQuestion : selectAll) {
				list.add(userQuestion.getQuestion());
			}

			putRequestValue("list", list);
			putRequestValue("listSize", list.size());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "forward:/qiantai/cuoti.jsp";
	}

	@RequestMapping(value = "/kaoshi.do")
	public String kaoshi(String coursesel, String cartype) {
		putRequestValue("coursesel", coursesel);
		putRequestValue("cartype", cartype);
		try {
			List<Question> sessionPaper = (List<Question>) getSessionValue("examPaper");
			if (sessionPaper != null) {
				long start = (long) getSessionValue("examstarttime");
				long current = System.currentTimeMillis();
				Long temp = 45 * 60 - ((current - start) / 1000);
				putSessionValue("examtime", temp - 1);
				return "forward:/qiantai/kaoshi.jsp";
			}
			log.info("组卷.................");
			int max = 50;
			if (coursesel.equals("科目一")) {
				max = 100;
			}
			List<Question> list = questionService.selectAll(Question.class, MapUtil.createMap("coursesel", coursesel, "cxsel", "所有"));
			List<Question> templist = questionService.selectAll(Question.class, MapUtil.createMap("coursesel", coursesel, "cxsel", cartype));
			list.addAll(templist);
			if (list.size() == 0) {
				return "forward:/qiantai/kaoshi.jsp";
			}
			Collections.shuffle(list);
			List<Question> paper = new ArrayList<Question>();
			if (list.size() <= max) {
				paper.addAll(list);
			} else {
				Random ran = new Random();
				int index = ran.nextInt(list.size());
				for (int i = 0; i < 15; i++) {
					index = (index + i) % list.size();
					paper.add(list.get(index));
				}
			}

			putSessionValue("examPaper", paper);
			putSessionValue("examPaperSize", paper.size());
			putSessionValue("examstarttime", new Date().getTime());
			putSessionValue("examtime", 45 * 60);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "forward:/qiantai/kaoshi.jsp";
	}

	@RequestMapping(value = "/kaoshiend.do")
	public String kaoshiend(String ans) {
		List<Question> sessionPaper = (List<Question>) getSessionValue("examPaper");
		String[] ary = ans.split(",");
		int score = 0;
		for (int i = 0; i < sessionPaper.size(); i++) {
			Question q = sessionPaper.get(i);
			boolean cuo = checkAns(ary[i], q.getAnswer());
			if (cuo) {
				score += q.getScore();
			}
			questionService.updateUserAnswer(q, cuo, getWebUser());
		}
		putSessionValue("kaoshifen", score);
		getHttpSession().removeAttribute("examPaper");
		getHttpSession().removeAttribute("examPaperSize");
		getHttpSession().removeAttribute("examstarttime");
		getHttpSession().removeAttribute("examtime");
		return "redirect:/qiantai/kaoshiend.jsp";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/lianxi.do")
	public String lianxi(String coursesel, Integer qitemId, String cartype) {
		putRequestValue("coursesel", coursesel);
		putRequestValue("qitemId", qitemId);
		putRequestValue("cartype", cartype);
		putRequestValue("itemList", questionItemService.selectAll(QuestionItem.class, MapUtil.createMap("kemusel", coursesel)));
		try {
			List<Question> list = null;
			if (qitemId == null) {
				list = questionService.selectAll(Question.class, MapUtil.createMap("coursesel", coursesel, "cxsel", "所有"));
				List<Question> templist = questionService.selectAll(Question.class, MapUtil.createMap("coursesel", coursesel, "cxsel", cartype));
				list.addAll(templist);
			} else {
				list = questionService.selectAll(Question.class,
						MapUtil.createMap("coursesel", coursesel, "questionItemId", qitemId, "cxsel", "所有"));
				List<Question> templist = questionService.selectAll(Question.class,
						MapUtil.createMap("coursesel", coursesel, "questionItemId", qitemId, "cxsel", cartype));
				list.addAll(templist);
			}
			putRequestValue("list", list);
			putRequestValue("listSize", list.size());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "forward:/qiantai/lianxi.jsp";
	}

	@RequestMapping(value = "/lianxiAns.do")
	public String lianxiAns(String qid, String ans) {
		int id = Integer.valueOf(qid.substring("score_".length()));
		Question q = questionService.get(id);
		boolean cuo = checkAns(ans, q.getAnswer());
		questionService.updateUserAnswer(q, cuo, getWebUser());
		return null;
	}

	private boolean checkAns(String userAns, String quesAns) {
		if (userAns.length() != quesAns.length())
			return false;
		char[] c1 = userAns.toCharArray();
		char[] c2 = quesAns.toCharArray();
		Arrays.sort(c1);
		Arrays.sort(c2);
		for (int i = 0; i < c1.length; i++) {
			if (c1[i] != c2[i])
				return false;
		}
		return true;
	}

	@RequestMapping(value = "/list.do")
	public String list() {

		try {
			// 字段名称集合
			LinkedList<String> parmnames = new LinkedList<String>();
			// 字段值集合
			LinkedList<Object> parmvalues = new LinkedList<Object>();
			Page p = FieldUtil.createPage(request, Course.class, parmnames, parmvalues);

			Page page = courseService.selectPage(p, Course.class);
			session.setAttribute(Constant.SESSION_PAGE, page);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "forward:/qiantai/list.jsp";
	}

	@RequestMapping(value = "/index.do")
	public String index() {
		try {
			putRequestValue("imglist", indexImageService.selectAll());

			List<Course> list = courseService.selectAll(Course.class, "viewCount desc");
			if (list.size() > 8) {
				list = list.subList(0, 8);
			}
			putRequestValue("sugList", list);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "forward:/qiantai/index.jsp";
	}

	 

	@RequestMapping(value = "/getCourse.do")
	public String getCourse(int uid) {
		try {
			Course item = courseService.get(uid);
			putRequestValue("item", item);

			double itemScore = 5;

			List<CourseComment> list = courseCommentService.selectAll(CourseComment.class, MapUtil.createMap("courseId", uid), "id desc");
			double total = 0;
			for (CourseComment courseComment : list) {
				total += courseComment.getScore();
			}
			putRequestValue("commentList", list);
			if(total>0){
				itemScore = MathExtend.round(total/list.size(), 1);
			}

			putRequestValue("commentSize", list.size());

			List<Course> xglist = courseService.selectAll(Course.class, MapUtil.createMap("typesel", item.getTypesel()), "viewCount desc");
			if (xglist.size() > 5) {
				xglist = xglist.subList(0, 5);
			}
			putRequestValue("xglist", xglist);
			putRequestValue("itemScore", itemScore);

			courseService.updateView(item);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "forward:/qiantai/single.jsp";
	}

	@RequestMapping(value = "/addCourseComment.do")
	public String addCourseComment(CourseComment bean) {
		try {
			SimpleUser user = getWebUser();
			if (user == null) {
				putSessionValue("errorMessage", "请先登陆");
				return "redirect:/com/getCourse.do?uid=" + bean.getCourseId();
			}
			bean.setUserId(user.getId());
			bean.setAddDate(DateUtil.getCurrentTime());

			courseCommentService.addCourseComment(bean);
			putSessionValue("errorMessage", "评价成功");
		} catch (Exception e) {
			e.printStackTrace();
			putSessionValue("errorMessage", "评价失败");
		}
		return "redirect:/com/getCourse.do?uid=" + bean.getCourseId();
	}

	@RequestMapping(value = "/toUser.do")
	public String toUser() {
		try {
			if (getWebUser() == null) {
				return "redirect:/index.jsp";
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "main";
	}

	private SimpleUser getWebUser() {
		try {
			return getSimpleUser();
		} catch (Exception e) {
		}
		return null;
	}

}
